﻿using System;
using System.Net.Http;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WebDataExtractor
{
    public partial class Form1 : Form
    {
        private readonly HttpClient _httpClient;

        public Form1()
        {
            InitializeComponent();
            _httpClient = new HttpClient();
            _httpClient.Timeout = TimeSpan.FromSeconds(15);
            _httpClient.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0");
        }

        private async void btnExtract_Click(object sender, EventArgs e)
        {
            string url = txtUrl.Text.Trim();
            if (string.IsNullOrEmpty(url))
            {
                MessageBox.Show("请输入URL地址");
                return;
            }

            if (!Uri.TryCreate(url, UriKind.Absolute, out _))
            {
                MessageBox.Show("URL格式不正确");
                return;
            }

            try
            {
                btnExtract.Enabled = false;
                txtResult.Clear();

                string html = await FetchHtmlAsync(url);
                ExtractAndDisplayInfo(html);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"获取数据失败: {ex.Message}");
            }
            finally
            {
                btnExtract.Enabled = true;
            }
        }

        private async Task<string> FetchHtmlAsync(string url)
        {
            HttpResponseMessage response = await _httpClient.GetAsync(url);
            response.EnsureSuccessStatusCode();
            return await response.Content.ReadAsStringAsync();
        }

        private void ExtractAndDisplayInfo(string html)
        {
            // 提取手机号（中国大陆11位手机号）
            var phoneRegex = new Regex(@"(?<!\d)(1[3-9]\d{9})(?!\d)");
            var phones = phoneRegex.Matches(html);

            // 提取邮箱
            var emailRegex = new Regex(@"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}");
            var emails = emailRegex.Matches(html);

            // 显示结果
            StringBuilder sb = new StringBuilder();
            sb.AppendLine("=== 手机号码 ===");
            foreach (Match match in phones)
            {
                sb.AppendLine(match.Value);
            }

            sb.AppendLine("\n=== 邮箱地址 ===");
            foreach (Match match in emails)
            {
                sb.AppendLine(match.Value);
            }

            txtResult.Text = sb.ToString();
        }
    }
}